package com.example.demoapp.activity;

import static com.example.demoapp.bean.util.KeyBoardUtils.hintKeyboard;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.demoapp.R;
import com.example.demoapp.bean.Res;
import com.example.demoapp.config.URLs;
import com.example.demoapp.bean.util.JSONParser;
import com.example.demoapp.bean.util.StringUtils;
import com.example.demoapp.vollley.MySingleton;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RegisterActivity extends AppCompatActivity {

    private Context mContext;
    @BindView(R.id.user_name_reg)
    EditText user_name;
    @BindView(R.id.user_password_reg)
    EditText user_password;
    @BindView(R.id.user_phoneNum_reg)
    EditText user_phoneNum;
    @BindView(R.id.user_email_reg)
    EditText user_email;
    @BindView(R.id.user_nickname_reg)
    EditText user_nickName;
    @BindView(R.id.btn_reg)
    Button btn_register;
    @BindView(R.id.accept_reg)
    CheckBox checkBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);// bindview
        //绑定当前activity
        mContext = RegisterActivity.this;
        setHintKeyboardView(getWindow().getDecorView());
        // 绑定
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setTitle("注册");
            bar.setDisplayHomeAsUpEnabled(true);
            bar.setHomeButtonEnabled(true);
        }

        // 设置用户须知样式
        checkBox.setText(StringUtils.changeTextStyle("同意用户须知",2,6,Color.BLUE,Typeface.BOLD));

        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                btn_register.setClickable(isChecked);
                //根据是否选中修改buttom颜色
                if (isChecked){
                    btn_register.setBackgroundColor(ContextCompat.getColor(mContext,R.color.tab_top_background));
                }
                else{
                    btn_register.setBackgroundColor(ContextCompat.getColor(mContext,R.color.list_item_vote_color));
                }

            }
        });


        // 发起注册
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String userName = user_name.getText().toString().trim();
                String password = user_password.getText().toString().trim();
                String phonenumber = user_phoneNum.getText().toString().trim();
                String email = user_email.getText().toString().trim();
                String nickName = user_nickName.getText().toString().trim();
                // 检查用户名和密码是否为空
                if (TextUtils.isEmpty(nickName) ||TextUtils.isEmpty(userName) || TextUtils.isEmpty(password) || TextUtils.isEmpty(phonenumber) || TextUtils.isEmpty(email)) {
                    Toast.makeText(RegisterActivity.this, "所有选项不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                //检查输入项
                if(!StringUtils.isChinaPhoneLegal(phonenumber)) {
                    Toast.makeText(RegisterActivity.this, "请输入正确手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!StringUtils.isEmail(email)) {
                    Toast.makeText(RegisterActivity.this, "请输入正确邮箱", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!btn_register.isEnabled()){
                    Toast.makeText(RegisterActivity.this, "请阅读用户须知并同意", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map map=new HashMap();
                // 输入参数
                map.put("userName", userName);//Admin
                map.put("password", password);//123
                map.put("phonenumber", phonenumber);//Admin
                map.put("email", email);//123
                map.put("nickName", nickName);//123
                MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.Register, new JSONObject(map),
                        new Response.Listener() {
                            @Override
                            public void onResponse(Object response) {
                                Res res = JSONParser.parseJson(response.toString());
                                Log.d("login_response",res.toString());
                                if (res.isSuccess()){
                                    Toast.makeText(mContext, "注册成功", Toast.LENGTH_SHORT).show();
                                    // 跳转回去，用户数据回显
                                    //设置返回的数据
                                    Intent intent = new Intent();
                                    intent.putExtra("username", userName);//Admin
                                    intent.putExtra("password", password);//123
                                    intent.putExtra("phoneNum", phonenumber);//Admin
                                    intent.putExtra("nickName", nickName);//Admin
                                    intent.putExtra("email", email);//123
                                    setResult(3, intent);
                                    //关闭当前activity
                                    finish();
                                }else{
                                    Toast.makeText(mContext, "注册失败", Toast.LENGTH_SHORT).show();
                                    // 清空密码
                                    user_password.setText("");
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(mContext, "网络出错", Toast.LENGTH_SHORT).show();
                        // 清空密码
                        user_password.setText("");
                    }
                }));
            }
        });

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Intent intent=new Intent();
            intent.setClass(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            RegisterActivity.this.finish();
        }
        return false;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent=new Intent();
                intent.setClass(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
                RegisterActivity.this.finish();
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    /**
     * 设置点击软键盘之外区域，软键盘消失
     *
     * @param view
     */
    public void setHintKeyboardView(View view) {
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hintKeyboard((Activity) mContext);
                    user_name.clearFocus();
                    user_password.clearFocus();
                    user_email.clearFocus();
                    user_nickName.clearFocus();
                    user_phoneNum.clearFocus();
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setHintKeyboardView(innerView);
            }
        }
    }
}